<template>
    <div class="admin-announcements">
      <h2>公告管理</h2>
      <el-button type="primary" @click="openDialog('add')">发布新公告</el-button>
  
      <el-table :data="announcements" style="width: 100%; margin-top: 20px;" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="content" label="内容"></el-table-column>
        <el-table-column prop="publishDate" label="发布日期" width="120"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openDialog('edit', row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="announcements.length === 0 && !loading" description="暂无公告"></el-empty>
  
      <el-dialog
        v-model="dialogVisible"
        :title="dialogMode === 'add' ? '发布公告' : '编辑公告'"
        width="50%"
      >
        <el-form :model="currentAnnouncement" label-width="80px" ref="announcementFormRef">
          <el-form-item label="标题" prop="title" :rules="{ required: true, message: '请输入标题', trigger: 'blur' }">
            <el-input v-model="currentAnnouncement.title"></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="content" :rules="{ required: true, message: '请输入内容', trigger: 'blur' }">
            <el-input type="textarea" v-model="currentAnnouncement.content" :rows="4"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">
              {{ dialogMode === 'add' ? '发布' : '保存' }}
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, reactive } from 'vue'
  import { fetchAnnouncements, addAnnouncement, updateAnnouncement, deleteAnnouncement } from '../../api'
  import { ElMessage, ElMessageBox } from 'element-plus'
  
  const announcements = ref([])
  const dialogVisible = ref(false)
  const dialogMode = ref('add') // 'add' or 'edit'
  const currentAnnouncement = reactive({
    id: null,
    title: '',
    content: '',
    publishDate: ''
  })
  const announcementFormRef = ref(null)
  const loading = ref(false)
  
  const loadAnnouncements = async () => {
    loading.value = true
    try {
      const response = await fetchAnnouncements()
      if (response.data.success) {
        announcements.value = response.data.data
      } else {
        ElMessage.error(response.data.message || '获取公告失败！')
      }
    } catch (error) {
      ElMessage.error('加载公告出错！')
      console.error('Failed to fetch announcements:', error)
    } finally {
      loading.value = false
    }
  }
  
  const openDialog = (mode, data = null) => {
    dialogMode.value = mode
    if (mode === 'add') {
      Object.assign(currentAnnouncement, { id: null, title: '', content: '', publishDate: new Date().toISOString().slice(0, 10) })
    } else {
      Object.assign(currentAnnouncement, data)
    }
    dialogVisible.value = true
    announcementFormRef.value?.resetFields()
  }
  
  const handleSubmit = () => {
    announcementFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          let response
          if (dialogMode.value === 'add') {
            response = await addAnnouncement(currentAnnouncement)
          } else {
            response = await updateAnnouncement(currentAnnouncement.id, currentAnnouncement)
          }
  
          if (response.data.success) {
            ElMessage.success(response.data.message)
            dialogVisible.value = false
            await loadAnnouncements()
          } else {
            ElMessage.error(response.data.message || '操作失败！')
          }
        } catch (error) {
          ElMessage.error('请求出错！')
          console.error('Failed to submit announcement:', error)
        }
      } else {
        ElMessage.error('请填写完整的表单信息！')
      }
    })
  }
  
  const handleDelete = (id) => {
    ElMessageBox.confirm(
      '确定要删除这条公告吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      try {
        const response = await deleteAnnouncement(id)
        if (response.data.success) {
          ElMessage.success(response.data.message)
          await loadAnnouncements()
        } else {
          ElMessage.error(response.data.message || '删除失败！')
        }
      } catch (error) {
        ElMessage.error('请求出错！')
        console.error('Failed to delete announcement:', error)
      }
    }).catch(() => {})
  }
  
  onMounted(loadAnnouncements)
  </script>
  
  <style scoped>
  .admin-announcements {
    padding: 20px;
  }
  </style>